#include "kv_store.h"

SkipList *g_skipList;

static int compareChar(void* a, void* b)
{
    const char* str_a = (const char*)a;
    const char* str_b = (const char*)b;
    return strcmp(str_a, str_b); 
}

void skiplist_print(SkipList *slist)
{
    if (slist == NULL || slist->head == NULL)
    {
        return;
    }
    
    printf("skiplist max_level:%d\n",slist->max_level);

    for (int i = slist->max_level - 1; i >= 0; i--)
    {
        printf("level %d------",i+1);

        SkipListNode *cur = slist->head->level_next[i];
        while (cur != NULL)
        {
            char *k = (char*)cur->key;
            char *v = (char*)cur->value;
            printf("key:%s  value:%s\t",k,v);
            cur = cur->level_next[i];
        }
        printf("\n");
    }
}

int kvs_skiplist_create()
{
    g_compare_skiplist = compareChar;

    g_skipList = skiplist_init();
	return 0;
}

int kvs_skiplist_free(SkipList *skiplist)
{
    if (skiplist == NULL || skiplist->head == NULL)
    {
        return -1;
    }
    
    SkipListNode *node = skiplist->head->level_next[0];
    while (node != NULL)
    {
        skiplist_delete(skiplist, node->key);
        node = node->level_next[0];
    }
	return 0;
}

char *kvs_skiplist_get(SkipList *skiplist, char *key)
{
    char *v = (char*)skiplist_search(skiplist,key);
    if (v == NULL)
    {
        return NULL;
    }
    return v;
}

int kvs_skiplist_set(SkipList *skiplist, char *key, char *value)
{
    char *k = (char*)calloc(128,sizeof(char));
    char *v = (char*)calloc(128,sizeof(char));
    // memcpy(k,key,sizeof(key));
    // memcpy(v,value,sizeof(value));
    memcpy(k,key,strlen(key) + 1);
    memcpy(v,value,strlen(value) + 1);

    int res = skiplist_insert(skiplist,k,v);
    if(res == -1)
    {
        return -1;
    }
    else if (res == 1)
    {
        return 0;
    }
    else if (res == 0)
    {
        return 1;
    }
	return 0;
}

int kvs_skiplist_mod(SkipList *skiplist, char *key, char *value)
{
    int res = skiplist_modify(skiplist,key,value);
    return res;
}

int kvs_skiplist_del(SkipList *skiplist, char *key)
{
    int res = skiplist_delete(skiplist, key);
    if (res == 1)
    {
        return 0;
    }
    else if (res == -1 || res == 0)
    {
        return -1;
    }
	return 0;
}

int kvs_skiplist_exist(SkipList *skiplist, char *key)
{
    char *v = (char*)skiplist_search(skiplist,key);
    if (v == NULL)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}